//
//  QRCodeViewController.swift
//  DSWeibo
//
//  Created by liuzhu on 2018/11/10.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import UIKit
import AVFoundation
class QRCodeViewController: UIViewController,UITabBarDelegate {

    //容器高度
    @IBOutlet weak var containerHeightCons: NSLayoutConstraint!
    //冲击波顶部约束
    @IBOutlet weak var scanLineCons: NSLayoutConstraint!
    //冲击波视图
    @IBOutlet weak var scanLineView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        customTabBar.selectedItem = customTabBar.items![0]
        customTabBar.delegate = self;
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //开始扫描
        startScan()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
//        self.scanLineCons.constant = -self.containerHeightCons.constant
//        self.scanLineView.layoutIfNeeded()
//
//        UIView .animate(withDuration: 10, animations: {
//            self.scanLineCons.constant=self.containerHeightCons.constant
//            UIView.setAnimationRepeatCount(MAXFLOAT)
//            self.scanLineView.layoutIfNeeded()
//        })

    }
    
    @IBAction func closeBtnClick(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    @IBOutlet weak var customTabBar: UITabBar!
    
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        if item.tag==1 {
            print("二维码")
            self.containerHeightCons.constant = 300
        }else{
           self.containerHeightCons.constant = 150
            print("条形码")
        }
    }
    
    //扫描二维码
    private func startScan(){
        //判断是否能够将输入添加到会话中
        if (deviceInput != nil) {
            if !session.canAddInput(deviceInput!){
                return
            }
        }else
        {
            return
        }
        //判断是否能够将输出添加到会话中
        if !session.canAddOutput(output) {
            return
        }
        //将输入输出添加到会话中
        session.addInput(deviceInput!)
        session.addOutput(output)
        //设置输出能够解析的数据类型
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        //设置输出对象的代理，只要解析成功，就会通知代理
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        //添加预览图层
        view.layer.insertSublayer(previewLayer, at: 0)
        //添加绘制图层到预览图层上
        previewLayer.addSublayer(drawLayer)
        //告诉session开始扫描
        session.startRunning()
    }
    
    //会话
    private lazy var session:AVCaptureSession = AVCaptureSession()
    //输入设备
    private lazy var deviceInput:AVCaptureDeviceInput? = {
        //获取摄像头
       let device = AVCaptureDevice.default(for: AVMediaType.video)
        //创建输入对象
        do{
            let input = try AVCaptureDeviceInput(device: device!)
            return input
        }catch{
            print(error)
            return nil
        }
    }()
    
    //输出设备
    private lazy var output:AVCaptureMetadataOutput = AVCaptureMetadataOutput();
    
    //创建预览图层
    private lazy var previewLayer:AVCaptureVideoPreviewLayer = {
       let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = UIScreen.main.bounds
        return layer
    }()
    
    //用户创建边线的图层
    private lazy var drawLayer:CALayer = {
        let layer = CALayer()
        layer.frame = UIScreen.main.bounds
        return layer
    }()
}

extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
    //解析到数据就会调用
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection){
       //获取扫描到的数据
        if (metadataObjects.count != 0) {
            let obj:AVMetadataMachineReadableCodeObject=metadataObjects.last as! AVMetadataMachineReadableCodeObject
            print(obj.stringValue ?? "nil")
        }
        //获取扫描到的二维码位置
        for object in metadataObjects{
            if object is AVMetadataMachineReadableCodeObject{
               let codeObject = previewLayer.transformedMetadataObject(for: object) as!AVMetadataMachineReadableCodeObject
                print(codeObject)
                //绘制图形
                //drawCorners(codeObject: codeObject)
            }
        }
       // print(metadataObjects.last)
    }
    private func drawCorners(codeObject:AVMetadataMachineReadableCodeObject){
        if codeObject.corners.isEmpty
        {
            return
        }
        //创建一个图层
        let layer = CAShapeLayer()
        layer.lineWidth = 1
        layer.strokeColor = UIColor.green.cgColor
        layer.fillColor = UIColor.clear.cgColor
        //创建路径
        //layer.path = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 200, height: 200)).cgPath
        var index:Int = 0
        let path = UIBezierPath()
        var point = CGPoint.zero
        point = CGPoint(dictionaryRepresentation:codeObject.corners[index] as! CFDictionary)!
        path.move(to: point)
        index += 1
        while index < codeObject.corners.count{
            point = CGPoint(dictionaryRepresentation:codeObject.corners[index] as! CFDictionary)!
            index += 1
            path.addLine(to: point)
         }
        path.close()
        layer.path = path.cgPath
        //将绘制好的图层添加到drawLayer上
        drawLayer.addSublayer(layer)
    }
    
    
}
